package service

import (
	"choujiang/common/db"
	"fmt"
	"choujiang/common/models"
	"math/big"
	"crypto/rand"
	"encoding/json"
	"time"
)

const (
	RANDOM_PRIZE_USER_CASH = "BoxKey::leyouprizeusercash"
)

type RePrizeUser struct {
	Name   string `json:"name"`
	Coins  int64  `json:"coins"`
	Avatar string `json:"avatar"`
}

func GetPrizeUser() []RePrizeUser {
	reUser := make([]RePrizeUser, 0)
	key := RANDOM_PRIZE_USER_CASH
	if v := db.MainRedisClient.Exists(key); v.Val() == 1 {
		s := db.MainRedisClient.Get(key)
		err := json.Unmarshal([]byte(s.Val()), &reUser)
		fmt.Printf("GetPrizeUser Unmarshal err %s", err)
		if err == nil {
			return reUser
		}
	}
	user := make([]model.User, 0)
	err := db.MysqlEngine.SQL("select q1.nick_name,q1.head_img_url from user q1 inner join (select (min(q2.id) + round(rand()*(max(q2.id)-2 - min(q2.id)))) as id from user q2) as t on q1.id >= t.id where q1.nick_name <> '' and q1.head_img_url <> ''  limit 30").Find(&user)
	if err != nil {
		fmt.Printf("-----GetPrizeUser err: %s", err)
	}
	for i := 0; i < len(user); i++ {
		curUser := &RePrizeUser{
			Name:   user[i].NickName,
			Avatar: user[i].HeadImgUrl,
			Coins:  GenerateRandomCoins(2, 20),
		}
		reUser = append(reUser, *curUser)
	}
	if len(reUser) > 0 {
		cashStr, err := json.Marshal(reUser)
		if err == nil {
			db.MainRedisClient.Set(key, cashStr, time.Minute*5)
		}
	}
	return reUser
}

func GenerateRandomCoins(min, max int64) int64 {
	maxBigInt := big.NewInt(max)
	i, _ := rand.Int(rand.Reader, maxBigInt)
	if i.Int64() < min {
		GenerateRandomCoins(min, max)
	}
	return i.Int64()
}
